package com.tff.gmall.item.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.tff.gmall.beans.PmsProductSaleAttr;
import com.tff.gmall.beans.PmsSkuAttrValue;
import com.tff.gmall.beans.PmsSkuInfo;
import com.tff.gmall.service.PmsSkuInfoService;
import com.tff.gmall.service.SpuService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ItemController {

    @Reference
    private PmsSkuInfoService skuInfoService;
    @Reference
    private SpuService spuService;

    @RequestMapping(value = "index")
    public String index(ModelMap modelMap){

        List<String> list = new ArrayList<>();
        for (int i =0;i<5;i++){
            list.add("string"+i);
        }
        modelMap.put("list",list);
        modelMap.put("hello","hello gaoxinru");
        modelMap.put("check","1");

        return "index";
    }

    @RequestMapping(value = "{skuId}.html")
    public String index(@PathVariable String skuId, ModelMap modelMap, HttpServletRequest request){
        String ip = request.getRemoteAddr();
        PmsSkuInfo pmsSkuInfo = skuInfoService.getPmsSkuInfoBySkuId(skuId,ip);
        //sku对象
        modelMap.put("skuInfo",pmsSkuInfo);

        List<PmsProductSaleAttr> pmsProductSaleAttrs = spuService.spuSaleAttrListCheckBySku(pmsSkuInfo.getProductId(),pmsSkuInfo.getId());
        //销售属性
        modelMap.put("spuSaleAttrListCheckBySku",pmsProductSaleAttrs);

        //查询当前spu下面对应的sku及sku所对应的属性值
        List<PmsSkuInfo> skuSaleAttrValueListBySpu = skuInfoService.getSkuSaleAttrValueListBySpu(pmsSkuInfo.getProductId());
        Map<String,String> map = new HashMap<>();

        for (PmsSkuInfo skuInfo : skuSaleAttrValueListBySpu) {
            String k = "";
            String v = "";
            v = skuInfo.getId();
            for (PmsSkuAttrValue value: skuInfo.getSkuAttrValueList()){
                k += value.getId()+"|";
            }
            map.put(k,v);
        }

        String jsonString = JSON.toJSONString(map);
        modelMap.put("jsonString",jsonString);

        return "item";
    }

}
